<?php

class ItemUserModel extends DBModel
{
	protected $_table = '{{item_user}}';
	protected $_id = 'rid';
	
	public function getListByItemID($itemid, $isjoin = 1)
	{
		$where['select'] = 'iu.userid, sum(r.howmuch) as howmuch';
		$where['from'] = '{{item_user}} iu';
		$where['condition'] = 'iu.itemid = :itemid AND iu.isjoin = :isjoin';
		$where['join'] = 'left join {{reply}} r on r.userid = iu.userid and r.itemid = :itemid';
		$where['group'] = 'iu.userid';
		$where['order'] = 'howmuch desc';
		return $this->findAll($where, array(':itemid' => $itemid, ':isjoin' => $isjoin));
	}
	
	public function getByItemID($itemid, $isjoin = 1)
	{
		return $this->find('itemid = :itemid AND isjoin = :isjoin', array(':itemid' => $itemid, ':isjoin' => $isjoin));
	}
	
	public function delByItemID($itemid)
	{
		return $this->delete('itemid = :itemid', array(':itemid' => $itemid));
	}
	
	public function getItemIdByUserID($userid, $isjoin = 1)
	{
		$where['select'] = "GROUP_CONCAT(itemid)";
		$where['condition'] = 'userid = :userid AND isjoin = :isjoin AND itemid > 0';
		$params = array(':userid' => $userid, ':isjoin' => $isjoin);
		return $this->findScalar($where, $params);
	}
	
	public function save($userid, $itemid, $isjoin = 0)
	{
		$where['select'] = 'rid';
		$where['condition'] = 'userid = :userid and itemid = :itemid';
		$params = array(':userid' => $userid, ':itemid' => $itemid);
		if ($this->findScalar($where, $params) === false) {
			return $this->insert(array('userid' => $userid, 'itemid' => $itemid, 'isjoin' => $isjoin));
		}
		return false;
	}
}